<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/27
 * Time: 16:19
 */

namespace app\api\validate;


use app\lib\enum\OrderTypeEnum;
use app\lib\Exception\ParameterException;
use think\Request;
use think\Url;
use think\Validate;

class BaseValidate extends Validate
{
    public function toCheck()
    {
        // 获取所有参数
        $request = Request::instance();
        $param = $request->param();

        // 验证参数
        $result = $this->batch()->check($param);

        // 参数错误 抛出异常
        if (!$result) {
            // $error = $this->error;
            throw new ParameterException([
                'info' => $this->error
            ]);
        } else {
            return true;
        }
    }

    protected function checkType($value, $rule = '', $data = '', $filed = ''){
        if($value == OrderTypeEnum::Buy || $value == OrderTypeEnum::Recycle){
            return true;
        }
        return false;
    }

    protected function isPositiveInteger($value, $rule = '', $data = '', $filed = '')
    {
        if (($value + 0) > 0 && is_numeric($value) && is_int($value + 0)) {
            return true;
        }
        return false;
    }

    protected function checkISBN($value, $rule = '', $data = '', $filed = '')
    {
        if (is_numeric($value) && strlen($value) == config('setting.isbnLength')) {
            return true;
        }
        return false;
    }

    protected function isNotEmpty($value, $rule = '', $data = '', $filed = ''){
        if(empty($value)){
            return false;
        }
        return true;
    }

    protected function isMobile($value, $rule = '', $data = '', $filed = ''){
        $rule1 = '/^1[3-8]{1}[0-9]{9}$/';
        $rule2 = '/^0\d{2,3}\-\d{7,8}$/';
        $result1 = preg_match($rule1, $value);
        $result2 = preg_match($rule2, $value);
        if ($result1 || $result2) {
            return true;
        }
        return false;
    }

    public function getDataByRule($arrays)
    {
        // 不允许包含user_id或者uid，防止恶意覆盖user_id外键
        if(key_exists('uid',$arrays)||key_exists('user_id',$arrays)){
            throw new ParameterException([
                'info'=>'参数中包含有非法的参数名user_id或者uid'
            ]);
        }

        $newArray = [];
        foreach ($this->rule as $key => $value){
            $newArray[$key] = $arrays[$key];
        }
        return $newArray;
    }
}